<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-edit" size="small" @click.stop="handleEdit(row)">编辑 </el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.stationManage_edit" @click="rowDel(row)">删除 </el-button>
        <el-button v-if="row.status == 0" type="text" size="small" icon="el-icon-circle-check" @click="handleEnbale(row)">启用</el-button>
        <el-button v-if="row.status == 1" type="text" size="small" icon="el-icon-circle-close" @click="handleDisable(row)">禁用</el-button>
        <el-button type="text" icon="el-icon-setting" size="small" @click.stop="openSelectStation(row)">所属工段</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addBtn">新增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.stationManage_edit" @click="handleDelete">删 除 </el-button>
      </template>
      <template #workSectionIdSearch="{}">
        <el-cascader
          v-model="search.workSectionId"
          :options="workSectionList"
          :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"
          :show-all-levels="false"
          filterable
          clearable
        ></el-cascader>
      </template>
    </avue-crud>
    <el-dialog
      ref="dialog"
      title="所属工段"
      append-to-body
      v-if="showSelectSectionDialog"
      :visible.sync="showSelectSectionDialog"
      :close-on-click-modal="false"
      :before-close="selectSectionDialogClose"
      width="30%"
    >
      <el-form label-width="90px" label-position="right" :rules="rules">
        <el-form-item label="所属工段:" prop="workSectionId">
          <el-cascader
            @change="handleChangeSection"
            v-model="selectWorkSectionForm.workSectionId"
            :options="workSectionList"
            :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"
            :show-all-levels="false"
            placeholder="请选择所属工段"
            popper-class="sectionPopper"
            filterable
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="排序号:">
          <el-input-number v-model="selectWorkSectionForm.sectionWorkstationSequence" controls-position="right" :min="undefined" :precision="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitWorkSection"><i class="el-icon-check"></i><span>保 存</span></el-button>
        <el-button
          size="small"
          @click="
            showSelectSectionDialog = false;
            selectWorkSectionForm.workSectionId = '';
          "
          ><i class="el-icon-circle-close"></i><span>关 闭</span></el-button
        >
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getStationtList,
  getWorkStationDetail,
  removeStationtInfo,
  getAllSection,
  saveWorkSection,
  checkWorkstation,
  workstationEnable,
  workstationDisable
} from '@/api/product/station-manage';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'ProductModelManageStationManage',
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'STATION_MANAGE',
      form: {},
      query: {},
      search: {},
      timer: new Date().getTime(),
      addDialog: false,
      editDialog: false,
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 406px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        menuWidth: '250px',
        column: [
          {
            label: '名称',
            prop: 'name',
            overHidden: true,
            search: true
          },
          {
            label: '工站类型',
            prop: 'type',
            type: 'select',
            search: true,
            width: 80,
            dicData: [
              //可做返回类型的转换
              {
                label: '过站',
                value: 'OVERSTATION'
              },
              {
                label: '报工',
                value: 'TIMESHEET'
              },
              {
                label: '测试',
                value: 'TEST'
              },
              {
                label: '老化',
                value: 'AGING'
              },
              {
                label: '包装',
                value: 'PACKING'
              },
              {
                label: '组装',
                value: 'ASSEMBLY'
              },
              {
                label: '上料',
                value: 'FEEDING'
              }
            ]
          },
          {
            label: '所属工段',
            prop: 'sectionName'
          },
          {
            label: '所属工段',
            prop: 'workSectionId',
            search: true,
            hide: true
          },
          {
            label: '编码',
            prop: 'code',
            width: 250
          },
          {
            label: '客户端',
            prop: 'clientType',
            type: 'select',
            search: true,
            width: 80,
            dicData: [
              {
                label: 'WEB',
                value: 'WEB'
              },
              {
                label: 'PDA',
                value: 'PDA'
              }
            ]
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            width: 60,
            dicData: [
              {
                label: '启用',
                value: 1
              },
              {
                label: '禁用',
                value: 0
              }
            ],
            search: true,
            html: true,
            formatter: (val) => {
              if (val.status == 0) {
                return '<b style="color:red">禁用</b>';
              } else {
                return '<b style="color:#70b603">启用</b>';
              }
            }
          },
          {
            label: '备注',
            prop: 'remark',
            overHidden: true
          },
          {
            label: '创建时间',
            prop: 'createTime',
            width: 150
          },
          {
            label: '最后更改时间',
            prop: 'updateTime',
            width: 150
          }
        ]
      },
      data: [],
      properties: {}, //表单
      title: '',
      showSelectSectionDialog: false,
      selectWorkSectionForm: {
        workSectionId: ''
      },
      flatSectionList: [],
      workSectionList: [],
      rowId: '',
      rules: {
        workSectionId: [{ required: true, message: '请选择所属工段', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    getAllSection().then(
      (res) => {
        this.workSectionList = this._get(res, 'data.data', []);
      },
      (error) => {
        this.workSectionList = [];
      }
    );
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.stationManage_add, false),
        delBtn: this.vaildData(this.permission.stationManage_delete, false),
        editBtn: this.vaildData(this.permission.stationManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 表单重置
     */
    emptytChange() {},
    reset() {
      this.addDialog = false;
      this.$refs.addProperties.resetForm();
    },
    /**
     * 跳转工站UI界面设计进行新增
     */
    addBtn() {
      this.title = '新增';
      // this.addDialog = true;
      this.$router.replace({ path: '/product/model-manage/stationui-design/index', query: { type: 'station' } });
    },
    /**
     * 跳转工站UI界面设计进行编辑
     */
    handleEdit(row) {
      let stationId = this._get(row, 'id', '');
      this.$router.replace({ path: '/product/model-manage/stationui-design/edit', query: { type: 'station', stationId: stationId } });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeStationtInfo(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0 && !row.id) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeStationtInfo(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开avue-crud之前的调用
     */
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getWorkStationDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.descs = 'create_time';
      getStationtList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    handleChangeSection(value) {
      let findSection = this.flatSectionList.find((item) => item.id == value);
      if (findSection) {
        this.$set(this.selectWorkSectionForm, 'sectionName', findSection.name);
      }
    },
    openSelectStation(row) {
      this.rowId = row.id;
      this.selectWorkSectionForm.workSectionId = row.sectionId;
      this.selectWorkSectionForm.sectionName = row.sectionName;
      this.selectWorkSectionForm.sectionWorkstationSequence = row.sectionWorkstationSequence === null ? undefined : row.sectionWorkstationSequence;
      this.showSelectSectionDialog = true;
      getAllSection().then(
        (res) => {
          this.workSectionList = this._get(res, 'data.data', []);
          this.flatSectionList = formatterSection(this.workSectionList);
          function formatterSection(data) {
            let arr = [];
            data.forEach((item) => {
              arr.push({
                name: item.name,
                id: item.id
              });
              if (item.children && item.children.length > 0) {
                item.children.forEach((citem) => {
                  arr.push({
                    name: citem.name,
                    id: citem.id
                  });
                });
              }
            });
            return arr;
          }
        },
        (error) => {
          this.workSectionList = [];
        }
      );
    },
    submitWorkSection() {
      if (!this.selectWorkSectionForm.workSectionId) {
        this.$message.warning('请选择所属工段!');
        return;
      }
      if (
        this.selectWorkSectionForm.sectionWorkstationSequence == 0 ||
        (this.selectWorkSectionForm.sectionWorkstationSequence && Number(this.selectWorkSectionForm.sectionWorkstationSequence)) < 1
      ) {
        this.$message.warning('排序号为正整数!');
        return;
      }
      let data = {
        id: this.rowId,
        sectionName: this.selectWorkSectionForm.sectionName,
        sectionId: this.selectWorkSectionForm.workSectionId,
        sectionWorkstationSequence: this.selectWorkSectionForm.sectionWorkstationSequence
      };
      if (!data.sectionWorkstationSequence) {
        delete data.sectionWorkstationSequence;
      }
      saveWorkSection(data).then((res) => {
        this.showSelectSectionDialog = false;
        this.$message.success(res.data.msg);
        this.onLoad(this.page);
      });
    },
    selectSectionDialogClose(done) {
      this.selectWorkSectionForm.workSectionId = '';
      done();
    },
    handleEnbale(row) {
      workstationEnable(row.id).then((res) => {
        this.$message.success(res.data.msg);
        this.onLoad(this.page);
      });
    },
    handleDisable(row) {
      checkWorkstation(row.id)
        .then((res) => {
          let data = res.data.data;
          let msg = '';
          if (data) {
            msg = '请确认是否禁用该工序?';
          } else {
            msg = '该工序已经被使用在工艺路线中，请确认是否禁用?';
          }
          this.$confirm(msg, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            workstationDisable(row.id).then((res) => {
              this.$message.success(res.data.msg);
              this.onLoad(this.page);
            });
          });
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};
</script>

<style></style>
